package com.qu.waibao.nearby;

import android.content.Intent;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.navi.BaiduMapAppNotSupportNaviException;
import com.baidu.mapapi.navi.BaiduMapNavigation;
import com.baidu.mapapi.navi.NaviParaOption;
import com.othershe.nicedialog.BaseNiceDialog;
import com.othershe.nicedialog.NiceDialog;
import com.othershe.nicedialog.ViewConvertListener;
import com.othershe.nicedialog.ViewHolder;
import com.qu.waibao.AppConfig;
import com.qu.waibao.MyApplication;
import com.qu.waibao.R;
import com.qu.waibao.baidu.LocationUtils;
import com.qu.waibao.base.BaseActivity;
import com.qu.waibao.base.BaseRecyclerAdapter;
import com.qu.waibao.bean.ShopDetail;
import com.qu.waibao.interf.XnetCallBack;
import com.qu.waibao.network.ActionUtil;
import com.qu.waibao.network.NetManager;
import com.qu.waibao.utils.BaiduUtil;
import com.qu.waibao.utils.GsonUtil;
import com.qu.waibao.utils.ImageLoader;
import com.qu.waibao.widget.RecyclerRefreshLayout;

import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

public class ShopindroceActivity extends BaseActivity implements View.OnClickListener,
        RecyclerRefreshLayout.SuperRefreshLayoutListener{
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.iv_publish)
    ImageView iv_publish;
    @BindView(R.id.mRecyclerRefreshLayout)
    RecyclerRefreshLayout mRecyclerRefreshLayout;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.iv_photo)
    CircleImageView circleImageView;
    @BindView(R.id.tv_name)
    TextView tv_name;
    @BindView(R.id.tv_amount)
    TextView tv_amount;
    @BindView(R.id.tv_score)
    TextView tv_score;
    @BindView(R.id.tv_main_bussiness)
    TextView tv_main_bussiness;
    @BindView(R.id.tv_second_business)
    TextView tv_second_business;
    @BindView(R.id.tv_address)
    TextView tv_address;
    private CommentAdapter adapter;
    private int pageNum = 1;
    private boolean isRefreshing = true;
    private ShopPerson shopPerson;
    private String longitude = "";
    private String latitude = "";
    private String userid = "";
    private double curLatitude;
    private double curLongitude;
    private String address = "";
    @Override
    protected boolean initBundle(Bundle bundle) {
        if(bundle != null){
            shopPerson = (ShopPerson) bundle.getSerializable("ShopPerson");
        }
        return super.initBundle(bundle);
    }

    @Override
    protected int getContentView() {
        return R.layout.activity_shopindroce;
    }

    @Override
    protected void initWidget() {
        super.initWidget();
        tv_title.setText("商家介绍");
        iv_publish.setVisibility(View.GONE);
        mRecyclerRefreshLayout.setColorSchemeResources(R.color.colorPrimaryDark);
        mRecyclerRefreshLayout.setSuperRefreshLayoutListener(this);
        if(shopPerson != null){
            longitude = shopPerson.getLongitude();
            latitude = shopPerson.getLatitude();
            userid = shopPerson.getUserid();
            address = shopPerson.getAddress_full();
            Log.e("TAG",longitude+":"+latitude);
        }
        if(LocationUtils.Mylocation != null){
            curLatitude = LocationUtils.Mylocation.getLatitude();
            curLongitude = LocationUtils.Mylocation.getLongitude();
        }
    }

    @Override
    protected void initData() {
        super.initData();
        adapter= new CommentAdapter(this, BaseRecyclerAdapter.ONLY_FOOTER);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setNestedScrollingEnabled(false);
        recyclerView.setAdapter(adapter);
        requestData();
    }
    @OnClick({R.id.ll_back,R.id.tv_dang})
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ll_back:
                finish();
                break;
            case R.id.tv_dang:
                NiceDialog.init()
                        .setLayoutId(R.layout.daohang_layout)     //设置dialog布局文件
                        .setConvertListener(new ViewConvertListener() {     //进行相关View操作的回调
                            int flag = 0;
                            @Override
                            public void convertView(ViewHolder holder, final BaseNiceDialog dialog) {
                                final TextView tv_gaode = holder.getView(R.id.tv_gaode);
                                final TextView tv_baidu = holder.getView(R.id.tv_baidu);
                                holder.setOnClickListener(R.id.tv_gaode, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        tv_gaode.setTextColor(Color.parseColor("#f29f1b"));
                                        tv_baidu.setTextColor(Color.parseColor("#333333"));
                                        flag = 1;
                                    }
                                });
                                holder.setOnClickListener(R.id.tv_baidu, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        tv_gaode.setTextColor(Color.parseColor("#333333"));
                                        tv_baidu.setTextColor(Color.parseColor("#f29f1b"));
                                        flag = 2;
                                    }
                                });
                                holder.setOnClickListener(R.id.tv_cancel, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        dialog.dismiss();
                                    }
                                });
                                holder.setOnClickListener(R.id.tv_sure, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        dialog.dismiss();
                                        if(flag == 1){
                                            gaodeNav(curLatitude,curLongitude,address);
                                        }else if(flag == 2){
                                            startNavi(curLatitude,curLongitude,Double.valueOf(latitude),Double.valueOf(longitude));
                                        }
                                    }
                                });
                            }
                        })
                        .setMargin(30)
                        .setDimAmount(0.3f)     //调节灰色背景透明度[0-1]，默认0.5f
                        .setShowBottom(false)     //是否在底部显示dialog，默认flase
                        .setOutCancel(true)     //点击dialog外是否可取消，默认true
                        .show(getSupportFragmentManager());     //显示dialog
                break;
        }
    }


    public void requestData(){
        Map<String,String> map = new HashMap<>();
        map.put("action", ActionUtil.shop_detail_get);
        map.put("userid", userid);
        map.put("longitude",longitude);
        map.put("latitude",latitude);
        map.put("pagenum",pageNum+"");
        NetManager.getInstance().request(this, map, true, new XnetCallBack() {
            @Override
            public void onSuccess(String result, String msg) {
                ShopDetail shopDetail = GsonUtil.createGson().fromJson(result,ShopDetail.class);
                if(!TextUtils.isEmpty(shopDetail.getDetail().getPhoto())){
                    ImageLoader.loadImage(getImageLoader(),circleImageView,
                            NetManager.getFullUrl(shopDetail.getDetail().getPhoto()),
                            R.drawable.shjs_touxiang,R.drawable.shjs_touxiang);
                }
                tv_name.setText(shopDetail.getDetail().getName());
                tv_amount.setText("接单量："+shopDetail.getDetail().getJiedan_total());
                if(!TextUtils.isEmpty(shopDetail.getDetail().getScore_avg())){
                    tv_score.setText(shopDetail.getDetail().getScore_avg()+"分");
                }else {
                    tv_score.setText("0.0分");
                }
                tv_main_bussiness.setText(shopDetail.getDetail().getBusiness_main());
                tv_second_business.setText(shopDetail.getDetail().getBusiness_second());
                tv_address.setText(shopDetail.getDetail().getAddress_full());
                if(isRefreshing){
                    adapter.clear();
                    adapter.addAll(shopDetail.getCommentlist());
                    if(shopDetail.getCommentlist().size() < 12){
                        adapter.setState(BaseRecyclerAdapter.STATE_NO_MORE,true);
                    }
                }else {
                    adapter.addAll(shopDetail.getCommentlist());
                    if(shopDetail.getCommentlist().size() < 12){
                        adapter.setState(BaseRecyclerAdapter.STATE_NO_MORE,true);
                    }
                    if(shopDetail.getCommentlist().size() == 0){
                        pageNum--;
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
               if(pageNum > 1 ){
                   pageNum--;
                   onComplate();
               }
            }

            @Override
            public void onFinished() {
               onComplate();
            }
        });
    }

    @Override
    public void onRefreshing() {
        isRefreshing = true;
        pageNum = 1;
        requestData();
    }

    @Override
    public void onLoadMore() {
        isRefreshing = false;
        pageNum++;
        adapter.setState(BaseRecyclerAdapter.STATE_LOAD_MORE,true);
        requestData();
    }
    public void onComplate(){
        mRecyclerRefreshLayout.onComplete();
        isRefreshing = false;
    }

    //开启百度导航
    public void startNavi(double LATITUDE_QIDIAN,double LONGTITUDE_QIDIAN,double endLag,double endLng) {
        LatLng ll_location = new LatLng(LATITUDE_QIDIAN,LONGTITUDE_QIDIAN);
        LatLng ll = new LatLng(endLag,endLng);
        NaviParaOption para = new NaviParaOption();
        para.startPoint(ll_location);
        para.startName("从这里开始");
        para.endPoint(ll);
        para.endName("到这里结束");
        try {
            BaiduMapNavigation.openBaiduMapNavi(para, this);
        } catch (BaiduMapAppNotSupportNaviException e) {
            e.printStackTrace();
            Toast.makeText(this, "您尚未安装百度地图客户端", Toast.LENGTH_LONG).show();
        }
    }


    public void gaodeNav(double LATITUDE_B,double LONGTITUDE_B,String end){
        Intent intent;
        if(BaiduUtil.isAvilible(getApplicationContext(),"com.autonavi.minimap")){ //传入指定应用包名
            try {
                intent = Intent.getIntent("androidamap://route?sourceApplication=softname&sname=我的位置&dlat="+LATITUDE_B+"&dlon="+LONGTITUDE_B+"&dname="+end+"&dev=0&m=0&t=1");
                startActivity(intent); //启动调用
            } catch (Exception e) {
            }
        }else{
            Toast.makeText(this, "您尚未安装高德地图客户端", Toast.LENGTH_LONG).show();
        }
    }
}
